package com.yww.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yww.entity.Users;
import com.yww.entity.UsersParam;
import com.yww.mapper.UsersMapper;
import com.yww.service.UsersService;
import com.yww.utils.MD5;
import com.yww.utils.PhotoUtil;
import com.yww.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户 控制层
 * 杨雯雯
 */
@RestController
public class UsersController {
    @Autowired
    UsersService usersService;
    @Autowired
    UsersMapper usersMapper;
    private Map<String,Object> map=new HashMap<String, Object>();

    /**
     * (查) 多条件分页查询用户
     * @param usersParam
     * @return
     */
    @RequestMapping("/getUsersList")
   public Object getUsersList(UsersParam usersParam,@RequestParam(required = false,defaultValue = "1")Integer page,@RequestParam(required = false,defaultValue = "10") Integer limit){
       //分页-需要分页的配置文件
       Page<Users> p = new Page<>(page,limit);
       //多条件
       QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
       if(!StringUtils.isEmpty(usersParam.getLoginName())) {
           queryWrapper.like("login_name", usersParam.getLoginName());
       }
       if(!StringUtils.isEmpty(usersParam.getStartTime())) {
           queryWrapper.gt("create_time", usersParam.getStartTime());
       }
       if(!StringUtils.isEmpty(usersParam.getEndTime())) {
           queryWrapper.lt("create_time", usersParam.getEndTime());
       }
       if(!StringUtils.isEmpty(usersParam.getIsLockOut())) {
           queryWrapper.eq("is_lock_out", usersParam.getIsLockOut());
       }
       if(!StringUtils.isEmpty(usersParam.getOrderBy()) && usersParam.getOrderBy().equals("createTime")) {
           queryWrapper.orderByDesc("create_time",usersParam.getCreateTime()); //字段名
       }
        if(!StringUtils.isEmpty(usersParam.getOrderBy()) && usersParam.getOrderBy().equals("lastLoginTime")) {
            queryWrapper.orderByDesc("last_login_time",usersParam.getLastLoginTime()); //字段名
        }
        if(!StringUtils.isEmpty(usersParam.getQdBeforeTime())) {
            queryWrapper.gt("qd_time", usersParam.getQdBeforeTime());
        }
        if(!StringUtils.isEmpty(usersParam.getQdAfterTime())) {
            queryWrapper.lt("qd_time", usersParam.getQdAfterTime());
        }
        if(!StringUtils.isEmpty(usersParam.getQdStatic())) {
            queryWrapper.eq("qd_static", usersParam.getQdStatic());
        }
        queryWrapper.eq("is_delete",0 );

       //查询方法
       IPage<Users> ipage = usersService.page(p, queryWrapper);
       //获取数据和总条数
       List<Users> data = ipage.getRecords();
       long total = ipage.getTotal();
       return new Result(0,"",total,data);
   }

    /**
     * 咨询师查看所分配的学生
     * @param usersParam
     * @return
     */
   @RequestMapping("/getCon")
   public Object getCon(UsersParam usersParam){
       List<Users> con = usersService.getCon(usersParam);

       usersParam.setLimit(null);
       usersParam.setPage(null);
       List<Users> con1 = usersService.getCon(usersParam);
       if(con!=null){
           return new Result(0,"查询成功", con1.size(),con);
       }else {
           return new Result(1,"查询失败");
       }

   }



    /**
     * (增) 添加用户信息
     * @param users
     * @return
     */
   @RequestMapping("/addUsers")
   public Object addUsers(@Valid Users users){
       List<Users> userNameByLoginName = usersService.getUserNameByLoginName(users);
       Date date = new Date();
       SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       if(userNameByLoginName!=null && userNameByLoginName.size()>0){
           return new Result(2,"该用户已存在");
       }else{
           users.setCreateTime(sdf.format(date));
           users.setIsLockOut("否");
           String str= MD5.getInstance().getMD5(users.getPassWord());
           users.setPassWord(str);
           boolean save = usersService.save(users);
           if(save){
               return new Result(0,"添加成功");
           }
           return new Result(1,"添加失败");
       }

   }


    /**
     * 修改用户信息
     * @param users
     * @return
     */
   @RequestMapping("/updUsers")
   public Object updUsers(@Valid Users users){
       boolean b = usersService.updateById(users);
       if(b){
           return new Result(0,"修改成功");
       }
           return new Result(1,"修改失败");
   }


    /**
     * 用户资料软删除
     * @param
     * @return
     */
   @RequestMapping("/delUsers")
   public Object delUsers(@RequestParam Integer userId){
       List<Users> userContainsRole = usersService.getUserContainsRole(userId);
       if(userContainsRole.size()>0){
           return new Result(2,"该用户拥有角色 不能删除");
       }
       Users users=new Users();
       users.setUserId(userId);
       users.setIsDelete(1);
       boolean b = usersService.updateById(users);
       if(b){
           return new Result(0,"删除成功");
       }
           return new Result(1,"删除失败");
   }


    /**
     * 重置用户密码
     * @param users
     * @return
     */
   @RequestMapping("/resetUsersPsw")
   public Object resetUsersPsw(Users users,Integer id){
       List<String> nameByManager = usersService.getNameByManager(id);

       if(nameByManager.contains("管理员")){
           users.setPassWord("000000");
           String str= MD5.getInstance().getMD5(users.getPassWord());
           users.setPassWord(str);

           //boolean b=usersService.updateById(users);
           boolean b = usersService.updateById(users);
           if(b){
               return new Result(0,"重置用户密码成功");
           }
           return new Result(1,"重置失败");
       }
       return new Result(2,"抱歉 您还不是管理员....");
       }






    /**
     * 根据用户id锁定用户
     * @param id
     * @return
     */
    @RequestMapping("/lockUsers")
      public Object lockUsers(@RequestParam Integer id){
       Users users=new Users();
       //获取当前时间
        Date date=new Date();
       users.setLockTime(date);
       users.setUserId(id);
       users.setIsLockOut("是");
        boolean b = usersService.updateById(users);
        if(b){
              return new Result(0,"用户锁定成功");
          }
             return new Result(1,"用户锁定失败");
      }



    /**
     * 根据用户id解锁改用户
     */
    @RequestMapping("/unLockUsers")
    public Object unLockUsers(@RequestParam Integer id){
        Users users=new Users();
        users.setUserId(id);
        users.setIsLockOut("否");
        users.setPasWrongNum(0);
        usersService.emptyTime(id);

        boolean b = usersService.updateById(users);
        if(b){
            return new Result(0,"解锁用户成功");
        }
        return new Result(1,"解锁用户失败");
    }


    /**
     * 自动分配
     * @param
     * @return
     */
    @RequestMapping("/openAuto")
    public Object openAuto(Integer num) {
        List<Users> con = usersService.getCon(null);
        List<Integer> str=new ArrayList<Integer>();
        for(int i=0;i<con.size();i++) {
            str.add(i, con.get(i).getUserId());
        }
        Integer integer = usersService.updateOpenButton(str, num);
        if (integer>0) {
            return new Result(0, "已开启自动分配");
        }
        return new Result(1, "分配失败");
    }





    /**
     * (改)修改用户密码
     * @param loginName
     * @param
     * @return
     */
    @RequestMapping("/updatePassWord")
    public Object updatePassWord(String loginName,Users users,String oldPsw){

        Integer integer=null;
        String md5 = MD5.getInstance().getMD5(oldPsw);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        Users one = usersService.getOne(queryWrapper);
        if(one.getPassWord().equals(md5)){
            String str= MD5.getInstance().getMD5(users.getPassWord());
            users.setPassWord(str);
            integer = usersService.updatePassWord(users);

        }else{
            return new Result(2,"密码输入错误");
        }

        if(integer>0){
            return new Result(0,"修改成功");
        }
        return new Result(1,"修改失败");
        }


    /**
     * 用户签到
     * @param users
     * @return
     */
    @RequestMapping("/userIn")
    public Object userIn(Users users){
        Users qdStatic = usersService.getQdStatic(users);
        if(qdStatic.getQdStatic().equals(1)){
            return new Result(2,"您已签到过了...");
        }else{
            Integer integer = usersService.userIn(users);
            if(integer>0){
                return new Result(0,"签到成功");
            }
            return new Result(1,"签到失败");
        }

    }


    /**
     * 用户签退
     * @param users
     * @return
     */
    @RequestMapping("/userOut")
    public Object userOut(Users users,@RequestParam Integer userId){
        Users byId = usersService.getById(userId);

        if(byId.getQdStatic()!=1){
            return new Result(3,"Sorry 暂时没有什么好签退的...");
        }
        //不允许签退开始
        Date timeOne=new Date();
        Date timeTwo=new Date(byId.getQdTime().getTime()+60*1000*10);
        if(timeOne.before(timeTwo)){
            return new Result(4,"十分钟之内不能签退！");
        }
        //不允许签退结束
        Users qdStatic = usersService.getQdStatic(users);
        if(qdStatic.getQdStatic().equals(0)){
            return new Result(2,"已签退");
        }else{
            Integer integer = usersService.userOut(users);
            if(integer>0){
                return new Result(0,"签退成功");
            }
            return new Result(1,"签退失败");
        }
        }


    /**
     * (改)修改咨询师权重
     * @param users
     * @param
     * @return
     */
    @RequestMapping("/updateWeight")
    public Object updateWeight(Users users){
        Integer integer = usersService.updateWeight(users);
        if(integer>0){
            return new Result(0,"修改成功");
        }
        return new Result(1,"修改失败");
    }

    /**
     *
     * 统计图（按咨询师查）
     * 一个统计--全查
     * @return
     */
//    @RequestMapping("/getStatistic")
//    public Object getStatistic() {
//        List<String> months=usersService.getZxsNum();
//        List<Integer> persons=usersService.getPeoples();
//        List<Integer> tokenNums = usersService.getTokenNums();
//        EchatsRes echatsRes=new EchatsRes();
//        echatsRes.setxData(months);
//        echatsRes.setyData(persons);
//        //
//        echatsRes.setY2Data(tokenNums);
//        return echatsRes;
//    }


//    /**
//     *
//     * 统计图（按咨询师查）
//     * @return
//     */
//    @RequestMapping("/getStatistic2")
//    public Object getStatistic2() {
//        List<String> months=usersService.getZxsNum2();
//        List<Integer> persons=usersService.getPeoples2();
//        EchatsRes echatsRes=new EchatsRes();
//        echatsRes.setxData(months);
//        echatsRes.setyData(persons);
//        return echatsRes;
//    }

    @RequestMapping("/getUser")
    public Object getUser(Integer userId){
        Users byId = usersService.getById(userId);
        return byId;
    }

    /**
     * 用户拍照上传头像
     *
     * @return
     */
    @RequestMapping("/uploadHeadImg")
    public Object uploadHeadImg(String photo,Integer userId) {
        String[] split = photo.split(",");
        String s = split[1];

        String s1 = PhotoUtil.GenerateImage(s,userId,usersService);
        if (!s1.equals("")) {
            map.put("success", true);
            map.put("message", s1);
        }
        else{
            map.put("success",true);
        }
        return map;
    }


    /**
     * 前台用户头像修改
     *
     * @param
     * @return
     */
    @RequestMapping("/updateUserHp")
    public Object updateUserHp(Integer id,String imgurl) {
        Users u=new Users();
        u.setUserId(id);
        u.setImgUrl(imgurl);

        boolean update = usersService.update(u, new QueryWrapper<Users>().eq("user_id",id));
        if(update) {
            return new Result(0,"头像已上传成功");
        }
        return new Result(1,"头像上传失败");
    }

    @RequestMapping("/delBatchUserId")
    public Object delBatchId(String ids) {
        String[] id = ids.split(",");
        List<Users> userContainsRole = usersService.listByIds(Arrays.asList(id));
        if(userContainsRole!=null && userContainsRole.size()>0){
            return new Result(2,"某些用户拥有角色 不能删除");
        }

        Integer i = usersService.delBatchUserId(id);
        if(i>0){
            return new Result(0,"删除成功");
        }
        return new Result(1,"删除失败");
    }




}
